import { Component } from '@angular/core';
import { NavController, LoadingController, AlertController } from 'ionic-angular';
import { ClipBoardPage } from './clipboard/clipboard'
import { AlbumPage } from './album/album'
import { Camera, CameraOptions } from '@ionic-native/camera'
import { SQLite, SQLiteObject } from '@ionic-native/sqlite';
import { Toast } from '@ionic-native/toast';
import { PhotoLibrary } from '@ionic-native/photo-library';
declare var $ :any


@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
  private database: SQLiteObject
  private zancun_imgs: any = [] //暂存de所有图片对象的数组
  private albums: any = []  //按图片集名称分类图片对象的数组S
  private album_img: any = [] //每个图片集的第一张图片对象的集合
  private isShowKB: any = true
  private tool_name: any = '编辑'
  constructor(public navCtrl: NavController,
              public loadingCtrl: LoadingController,
              public alertCtrl: AlertController,
              private photoLibrary: PhotoLibrary,
              private camera: Camera,
              private sqlite: SQLite,
              private toast: Toast) {
    this.photoLibrary.requestAuthorization().then(() => {
    }).catch(err => console.log('permissions weren\'t granted'));
  }

  ionViewWillEnter() {
    this.initDB();
    
  }

  ionViewDidEnter() {
    
  }

  /**
   * 创建并打开本地数据库
   * 
   * @memberof HomePage
   */
  initDB(){
    this.sqlite.create({
      name: 'kj.db',
      location: 'default',
      // iosDatabaseLocation	: 'Library'
    })
    .then((db: SQLiteObject) => {
      db.executeSql('create table if not exists kj_imgs(id INTEGER PRIMARY KEY AUTOINCREMENT,'+
      'width INTEGER NOT NULL,'+
      'height INTEGER NOT NULL,'+
      'dataUrl TEXT NOT NULL,'+
      'albumname TEXT NOT NULL)',{})
      .then(()=> {
        console.log('Executed SQL')
        this.queryImgFromDB();
      })
      .catch(e => console.log(e));
      this.database = db;
      console.log(db);
      
    
    })
    .catch(e => console.log(e))
  }

/**
 * 获取本地数据库的已裁剪照片
 * 
 * @memberof HomePage
 */
  queryImgFromDB() {
    this.showLoading("加载中。。。");
    this.database.executeSql("SELECT * FROM kj_imgs",{}).then((data) => {
      this.albums = [];
      this.zancun_imgs = [];
      this.album_img = [];
      for(var i=0;i<data.rows.length;i++){
        this.zancun_imgs.push(data.rows.item(i))
      }
      
      console.log('data',data);
      console.log(this.zancun_imgs);
      if(this.zancun_imgs.length > 0) {
        this.isShowKB = false;
        var albumname_arr = [];
        this.zancun_imgs.forEach(e => {
          albumname_arr.push(e.albumname)
        });
        //找出图集的所有名称
        albumname_arr = Array.from(new Set(albumname_arr));
        console.log('albumname_arr',albumname_arr);
        albumname_arr.forEach(element => {
          var arr = this.zancun_imgs.filter(e => {
            return e.albumname === element;
          });
          this.albums.push(arr);
          this.album_img.push(arr[0]);
        });
        console.log(this.albums);
        this.hideLoading();
      }else{
        this.isShowKB = true;
      }
    },(err) => {console.log('查询错误')});
  }

  showDelIcon() {
    this.tool_name = this.tool_name == "编辑" ? "完成" : "编辑";
  }

  /**
   * 删除图集
   * 
   * @param {any} name 
   * @memberof HomePage
   */
  delAlbum(name) {
    this.database.executeSql("DELETE FROM kj_imgs WHERE albumname=?;", [name])
    .then(() => {
      this.queryImgFromDB();
    })
    .catch(e => console.log(e));//删除数据
  }

  /**
   * 从本地相册获取需要编辑的图片
   * 
   * @memberof HomePage
   */
  selectPicFromLocal() {
    const options: CameraOptions = this.getOptions(this.camera.DestinationType.DATA_URL);
    this.camera.getPicture(options).then((imageData) => {
      let base64Image = 'data:image/png;base64,' + imageData;
      // console.log(imageData);
      this.navCtrl.push(ClipBoardPage,{'pic':base64Image,'database':this.database});
    },(err) => {
      this.toast.show('请确保开启存储权限，并且选择jpg或png格式的图片。','4000','center').subscribe();
    });
  }
  
  /**
   * 获取照片的属性设置
   * 
   * @param {any} destinationType 
   * @returns 
   * @memberof HomePage
   */
  getOptions(destinationType){
    var options: CameraOptions = {
      quality: 100,
      sourceType: 0,
      destinationType: destinationType,
      encodingType: this.camera.EncodingType.PNG,
      mediaType: this.camera.MediaType.PICTURE
    }
    return options;
  }

  /**
   * 跳转至图集页
   * 
   * @param {any} index 
   * @memberof HomePage
   */
  openAlbum(index) {
    this.navCtrl.push(AlbumPage,{'zancun_album_imgs': this.albums[index],'database':this.database})
  }

  PromptEmpty() {
    this.toast.show("图集空白！动手剪辑并暂存吧。",'4000','center').subscribe();
  }

  /**
   * 显示loading
   * @param content 显示的内容
   */
  private loadingIsOpen:any;
  private loading:any;
  showLoading(content: string = ''): void {
    if (!this.loadingIsOpen) {
      this.loadingIsOpen = true;
      this.loading = this.loadingCtrl.create({
          content: content
      });
      this.loading.present();
      setTimeout(() => { //最长显示2秒
          this.loadingIsOpen && this.loading.dismiss();
          this.loadingIsOpen = false;
      }, 2000);
    }
  };

  /**
  * 关闭loading
  */
  hideLoading(): void {
    this.loadingIsOpen && this.loading.dismiss();
    this.loadingIsOpen = false;
  }
/**
 * 弹出对话框
 * 
 * @param {any} name 
 * @memberof HomePage
 */
showConfirmDelAlbum(name) {
    let confirm = this.alertCtrl.create({
      title: '提示',
      message: '是否删除 '+name+' 图集?',
      buttons: [
        {
          text: '再想想',
          handler: () => {

          }
        },
        {
          text: '确定',
          handler: () => {
            this.delAlbum(name);
          }
        }
      ]
    });
    confirm.present();
  }

  goTest(){
    this.navCtrl.push(AlbumPage);
  }
  goTestCli(){
    this.navCtrl.push(ClipBoardPage)
  }

}
